{
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "# 第一章 python基础应用\n",
        "\n",
        " #本章主要介绍一些在python的基础应用，主要从以下几个方面来介绍：\n",
        " \n",
        "一、 python基础路径\n",
        " * 路径操作\n",
        " * 模块引用\n",
        " \n",
        "二、 python常用语法结构\n",
        " * 运算逻辑符\n",
        " * 控制流语句 \n",
        " * 常用关键字\n",
        " * 其他python输入及格式化输出\n",
        " * lambda函数\n",
        " \n",
        "三、 python常用类型/序列函数\n",
        " * 列表\n",
        " * 字典\n",
        " * tuple\n",
        " * 元组\n",
        " * 常用序列函数\n"
      ],
      "metadata": {}
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 1.python基础路径\n",
        "### 1.1 路径操作"
      ],
      "metadata": {}
    },
    {
      "cell_type": "markdown",
      "source": [
        "### 1.1.1  绝对路径和相对路径\n",
        "文件路径就是文件在电脑中的位置，表示文件路径的方式有两种，相对路径和绝对路径。其中，相对路径就是相对于当前文件的路径，它相对于程序的当前工作目录；本地路径是指文件在硬盘上真正存在的路径，总是从根文件夹开始。\n",
        "\n",
        "在表示路径中我们常用点（.）和点点（..）文件夹，它们不是真正的文件夹，而是可以在路径中使用的特殊名称。单个的句点（“点”）用作文件夹目名称时，是“这个目录”的缩写。两个句点（“点点”）意思是父文件夹。"
      ],
      "metadata": {}
    },
    {
      "cell_type": "raw",
      "source": [],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "##处理绝对路径和相对路径\n",
        "import os\n",
        "print(os.path.abspath('.'))#返回一个相对路径的绝对路径\n",
        "print(os.path.abspath('.\\data'))#返回一个相对路径的绝对路径\n",
        "#检查一个路径是否绝对路径，如果是则返回true\n",
        "print(os.path.isabs('.'))\n",
        "print(os.path.isabs(os.path.abspath('.')))"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "F:\\jupyter\\浩彬分享的代码\n",
            "F:\\jupyter\\浩彬分享的代码\\data\n",
            "False\n",
            "True\n"
          ]
        }
      ],
      "execution_count": 2,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "print(os.path.abspath('.'))"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "F:\\jupyter\\浩彬分享的代码\n"
          ]
        }
      ],
      "execution_count": 3,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [],
      "outputs": [],
      "execution_count": 5,
      "metadata": {
        "collapsed": true
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "###  1.1.2 路径的生成与拼接"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#使用os.path.join生成路径\n",
        "from pathlib import  Path\n",
        "home = \"D:\\\\jupyter\"\n",
        "data_folder=os.path.join(home,\"python\",\"Code\")\n",
        "data_filename = os.path.join(data_folder,\"Chapter 2\",\"ionosphere.data\")\n",
        "print(data_filename)"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "D:\\jupyter\\python\\Code\\Chapter 2\\ionosphere.data\n"
          ]
        }
      ],
      "execution_count": 7,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "print('1:',Path()) #取当前路径\n",
        "print('2:',Path('a','b','c/d')) #字符合成\n",
        "print('3:',Path('/etc'))  #直接写入绝对路径"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "1: .\n",
            "2: a\\b\\c\\d\n",
            "3: \\etc\n"
          ]
        }
      ],
      "execution_count": 6,
      "metadata": {}
    },
    {
      "cell_type": "markdown",
      "source": [
        "#举例路径的生成与分解"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "### 创建新文件夹。如果中间路径的文件夹不存在，那么就会把中间文件夹创建上\n",
        "os.makedirs('C:\\\\onedrive\\\\jupyter\\\\testmkdir\\\\1')\n",
        "#也可以使用mkdir创建，但是中间目录必须存在，否则报错\n",
        "os.mkdir('C:\\\\onedrive\\\\jupyter\\\\testmkdir2\\\\2')"
      ],
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "collapsed": true
      }
    },
    {
      "cell_type": "code",
      "source": [
        "#举例路径的生成与分解\n",
        "p = Path('a','b','f/z')\n",
        "print(p)\n",
        "p2 = p / 'new_str'\n",
        "print(p2)\n",
        "p3 = '/new_str' / p\n",
        "print(p3)\n",
        "p4 = p3 / p\n",
        "print(p4)"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "a\\b\\f\\z\n",
            "a\\b\\f\\z\\new_str\n",
            "\\new_str\\a\\b\\f\\z\n",
            "\\new_str\\a\\b\\f\\z\\a\\b\\f\\z\n"
          ]
        }
      ],
      "execution_count": 8,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "p3.joinpath('etc','ab',Path('http')) # joinpath 拼接，等效于 p3.joinpath('etc','ab','http')"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 9,
          "data": {
            "text/plain": [
              "WindowsPath('/new_str/a/b/f/z/etc/ab/http')"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 9,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "print(p4.parts)#路径分割: parts方法"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "('\\\\', 'new_str', 'a', 'b', 'f', 'z', 'a', 'b', 'f', 'z')\n"
          ]
        }
      ],
      "execution_count": 10,
      "metadata": {}
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 获取路径"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "##路径的获取\n",
        "p4 = Path('/new_str/a/b/f/z/a/b/f/z')\n",
        "print(p4.parent)#获取目录\n",
        "print(p4.parents)#获取父目录\n",
        "\n",
        "for x in p4.parents:\n",
        "    print(x)"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\\new_str\\a\\b\\f\\z\\a\\b\\f\n",
            "<WindowsPath.parents>\n",
            "\\new_str\\a\\b\\f\\z\\a\\b\\f\n",
            "\\new_str\\a\\b\\f\\z\\a\\b\n",
            "\\new_str\\a\\b\\f\\z\\a\n",
            "\\new_str\\a\\b\\f\\z\n",
            "\\new_str\\a\\b\\f\n",
            "\\new_str\\a\\b\n",
            "\\new_str\\a\n",
            "\\new_str\n",
            "\\\n"
          ]
        }
      ],
      "execution_count": 14,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "str(p)"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 13,
          "data": {
            "text/plain": [
              "'\\\\etc'"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 13,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "p = Path('/etc')\n",
        "print(str(p),'\\n',bytes(p))"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\\etc \n",
            " b'\\\\etc'\n"
          ]
        }
      ],
      "execution_count": 11,
      "metadata": {}
    },
    {
      "cell_type": "markdown",
      "source": [
        "### 1.1.3 其它一些路径扩展操作"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "p = Path('/a/b/c/d/g.tar.gz.a')\n",
        "\n",
        "print(p.name) #取basename\n",
        "print(p.suffix) #取目录最后一部分的扩展名，最后一个小数点部分。包括小数点。\n",
        "print(p.suffixes) #取从左到右第一个小数点右侧的部分，小数点分割。每部分都带小数点。\n",
        "print(p.stem) #取basename 排除最后一个小数点部分\n",
        "print(p.with_name('233.tgz')) #补仓后缀\n",
        "print(p.with_suffix('.txt')) #补后缀"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "g.tar.gz.a\n",
            ".a\n",
            "['.tar', '.gz', '.a']\n",
            "g.tar.gz\n",
            "\\a\\b\\c\\d\\233.tgz\n",
            "\\a\\b\\c\\d\\g.tar.gz.txt\n"
          ]
        }
      ],
      "execution_count": 15,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "p = Path('../tmp/')\n",
        "print(p.cwd())  #获取当前所在目录\n",
        "print(p.home())  #获取当前用户的家目录\n",
        "print(p.is_dir()) #判断是否为目录\n",
        "print(p.is_file())#判断是否为文件\n",
        "print(p.is_symlink()) #判断是否为软连接\n",
        "print(p.is_socket()) #判断是否为socket 文件\n",
        "print(p.is_block_device()) #判断是否为块设备\n",
        "print(p.is_char_device()) #判断是否为字符设备\n",
        "print(p.is_absolute()) #判断是否为绝对路径\n",
        "print(p.resolve()) #返回绝对路径，推荐使用\n",
        "print(p.absolute()) #返回绝对路径 \n",
        "print(p.exists()) #判断文件或者目录是否存在"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "F:\\jupyter\\浩彬分享的代码\n",
            "C:\\Users\\x1c\n",
            "False\n",
            "False\n",
            "False\n",
            "False\n",
            "False\n",
            "False\n",
            "False\n",
            "F:\\jupyter\\tmp\n",
            "F:\\jupyter\\浩彬分享的代码\\..\\tmp\n",
            "False\n"
          ]
        }
      ],
      "execution_count": 16,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "p5 = Path('/b/b/c')\n",
        "p5.as_uri() #返回文件的uri\n",
        "\n",
        "#说明：不能使用相对路径"
      ],
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "collapsed": true
      }
    },
    {
      "cell_type": "code",
      "source": [
        "#设置路径变量\n",
        "p1 =Path('/jupyter/tmp/a/b')\n",
        "p2 =Path('/jupyter/tmp/a/b/3.txt')\n",
        "\n",
        "# 创建文件\n",
        "p1.mkdir(parents= True,exist_ok= True)\n",
        "p2.touch()\n",
        "\n",
        "# 检测文件是否创建成功\n",
        "print(p2.exists())\n",
        "\n",
        "#在a/b下创建新文件\n",
        "p1 /= 'readme.txt'\n",
        "p1.touch()\n",
        "print(p1)\n",
        "print(p1.exists())"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "True\n",
            "\\jupyter\\tmp\\a\\b\\readme.txt\n",
            "True\n"
          ]
        }
      ],
      "execution_count": 17,
      "metadata": {}
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 1.2 模块引用\n",
        "\n",
        "在Python中，模块就是一个有.py扩展名、包含Python代码的文件。一般分为import第三方库和自己创建的方法模块： \n",
        "### 1.2.1 引用第三方库"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "# 直接导入Python的内置基础数学库，当要使用其中的某个变量可以使用math.cos\n",
        "import math\n",
        "print(math.cos(math.pi))\n",
        "\n",
        "# 可以起个别名，方便使用或避免名字冲突\n",
        "import math as m\n",
        "print(m.cos(m.pi))\n",
        "\n",
        "# 从math中导入cos函数和pi变量,可以直接使用cos\n",
        "from math import cos, pi\n",
        "print(cos(pi))"
      ],
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "collapsed": true
      }
    },
    {
      "cell_type": "code",
      "source": [],
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "collapsed": true
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "### 1.2.2 引用创建的py文件\n",
        "#### 本文件为python基础，若调用同级目录，可以直接import  \n",
        "目录结构如下\n",
        "- script  \n",
        "  - --python基础  \n",
        "  - --myfun.py "
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#可以直接使用\n",
        "import myfun\n",
        "#myfun.add(3,4）"
      ],
      "outputs": [],
      "execution_count": 19,
      "metadata": {
        "collapsed": true
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "####  本文件为python基础，若调用子目录下的模块，需要增加from import  \n",
        "目录结构如下\n",
        "- script  \n",
        "  - --python基础  \n",
        "  - --myfun.py  \n",
        "  - --sub_fun  \n",
        "    - --sub_myfun.py"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "from sub_fun import sub_myfun\n",
        "sub_myfun.sub_add(4,5)"
      ],
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "collapsed": true
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "#### 本文件为python基础，若调用其他子目录下的模块，需要把所调用py文件对应上一级目录的路径添加到配置环境中，然后from import  \n",
        "目录结构如下\n",
        "- upp_fun  \n",
        "  - --upp_myfun\n",
        "- script  \n",
        "  - --python基础  \n",
        "  - --myfun.py  \n",
        "  - --sub_fun  \n",
        "    - --sub_myfun.py"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#指定路径\n",
        "import sys\n",
        "sys.path.append('C:\\\\onedrive\\\\jupyter')\n",
        "#应该也可以sys.path.append('..')\n",
        "from upp_fun import upp_myfun\n",
        "upp_myfun.upp_add(4,5)"
      ],
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "collapsed": true
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "### __init__.py 文件说明\n",
        "\n",
        "在python模块的每一个包中，都有一个__init__.py文件（这个文件定义了包的属性和方法）然后是一些模块文件和子目录，假如子目录中也有__init__.py 那么它就是这个包的子包了。当你将一个包作为模块导入的时候，实际上导入了它的__init__.py 文件。\n",
        "\n",
        "一个包是一个带有特殊文件 __init__.py 的目录。__init__.py 文件定义了包的属性和方法。其实它可以什么也不定义；可以只是一个空文件，但是必须存在。如果 __init__.py 不存在，这个目录就仅仅是一个目录，而不是一个包，它就不能被导入或者包含其它的模块和嵌套包。\n",
        "\n",
        "__init__.py 中还有一个重要的变量，叫做__all__。\n",
        "当全部导入模块时（from 模块 import *），import 就会把注册在包__init__.py 文件中 __all__ 列表中的子模块和子包导入到当前作用域中来\n",
        "\n",
        "__init__.py的作用：\n",
        "\n",
        "package的标识，不能删除\n",
        "定义package中的__all__，用来模糊导入\n",
        "编写Python代码(不建议在__init__中写python模块，可以在包中在创建另外的模块来写，尽量保证__init__.py简单）"
      ],
      "metadata": {}
    },
    {
      "cell_type": "markdown",
      "source": [
        "# 2. python常用语法结构\n",
        "## 2.1 python运算符\n",
        "https://www.runoob.com/python/python-operators.html\n",
        "* 算术运算符\n",
        "* 比较（关系）运算符\n",
        "* 赋值运算符\n",
        "* 逻辑运算符\n",
        "* 位运算符\n"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "a+b        a加b\n",
        "a-b        a减b\n",
        "a*b        a乘以b\n",
        "a/b        a除以b\n",
        "a//b       a除以b，结果只取整数部分\n",
        "a**b       a的b次幂\n",
        "a&b        a或b都为True，则为True；对于整数，取逐位AND\n",
        "a|b        a或b有一个为True，则为True；对于整数，取逐位OR\n",
        "a^b        对于布尔，a或b有一个为True，则为True，二者都为True，为False；对于整数，取逐位EXCLUSIVE-OR\n",
        "a==b       a等于b，则为True\n",
        "a!=b       a不等于b，则为True\n",
        "a<b，a<=b    a小于（或小于等于）b，则为True\n",
        "a〉b，a>=b   a大于（或大于等于）b，则为True\n",
        "a is b      a和b引用同一个Python对象，则为True\n",
        "a is not b   a和b引用不同的Python对象，则为True"
      ],
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "collapsed": true
      }
    },
    {
      "cell_type": "code",
      "source": [
        "#is比较与==运算符不同,s 检查的是两个对象是否相同，而不是相等\n",
        "a = b = [1,2,3]\n",
        "c = [1,2,3]\n",
        "a == b, a == c,a is b,a is c\n",
        "#变量 x 和 y 指向同一个列表，而c 指向另一个列表，虽然两个的值都是一样，但是并不是同一个对象，所以这里 a is c 返回 False"
      ],
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "collapsed": true
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 2.2 控制流语句\n",
        "### 2.2.1 for循环\n",
        "for循环是在一个集合（列表或元组）中进行迭代，或者就是一个迭代器。"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#range可以接受三个参数，分别是起始值，上限（不包括上限），步长\n",
        "for i in range(10,19,2):\n",
        "    print(i)\n",
        "\n",
        "#for循环在一行，[for]\n",
        "x= [1 for i in range(5)]\n",
        "x"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "10\n",
            "12\n",
            "14\n",
            "16\n",
            "18\n"
          ]
        },
        {
          "output_type": "execute_result",
          "execution_count": 21,
          "data": {
            "text/plain": [
              "[1, 1, 1, 1, 1]"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 21,
      "metadata": {}
    },
    {
      "cell_type": "markdown",
      "source": [
        "### 2.2.2 if、elif和else\n",
        "if是最广为人知的控制流语句。它检查一个条件，如果为True，就执行后面的语句。可以只使用if而不使用else\n",
        "可以使用if-elif-else的结构，中间可以包括多个elif。"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "##猜数字游戏\n",
        "import random\n",
        "print('请猜一个1-20的数字，你有6次机会')\n",
        "answer = random.randint(1,20)\n",
        "for i in range(1,3):\n",
        "    print('请输入：')\n",
        "    num = int(input())\n",
        "    if num > answer:\n",
        "        print(\"太大了，再猜一个\")\n",
        "    elif num < answer:\n",
        "        print('太小了，再猜一个')\n",
        "    else:\n",
        "        break\n",
        "if num == answer:\n",
        "    print('恭喜你猜中了！正确答案是%d' %answer )\n",
        "else:\n",
        "    print('已经超过限制次数了，正确答案是%d' %answer)"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "请猜一个1-20的数字，你有6次机会\n",
            "请输入：\n",
            "2\n",
            "太小了，再猜一个\n",
            "请输入：\n",
            "34\n",
            "太大了，再猜一个\n",
            "已经超过限制次数了，正确答案是5\n"
          ]
        }
      ],
      "execution_count": 1,
      "metadata": {}
    },
    {
      "cell_type": "markdown",
      "source": [
        "###  2.2.3While循环\n",
        "while循环指定了条件和代码，当条件为False或用break退出循环，代码才会退出"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "##使用标志\n",
        "#导致程序结束的事件有很多时，如果在一条while 语句中检查所有这些条件，将既复杂又困难。\n",
        "#在要求很多条件都满足才继续运行的程序中，可定义一个变量\n",
        "#用于判断整个程序是否处于活动状态。这个变量被称为标志 \n",
        "prompt = \"\\nTell me something, and I will repeat it back to you:\"\n",
        "prompt += \"\\nEnter 'quit' to end the program. \"\n",
        "active = True\n",
        "while active:\n",
        "    message = input(prompt)\n",
        "    if message == 'quit':\n",
        "        active = False\n",
        "    else:\n",
        "        print(message)"
      ],
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "collapsed": true
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "### 2.2.3 pass、continue、break"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#pass是Python中的非操作语句。代码块不需要任何动作时可以使用（作为未执行代码的占位符）；因为Python需要使用空白字符划定代码块，所以需要pass\n",
        "x=0\n",
        "if x < 0:\n",
        "    print('negative!')\n",
        "elif x == 0:\n",
        "    pass\n",
        "else:\n",
        "    print('positive!')\n",
        "\n",
        "#continue,跳过该次循环;if+continue,符合条件的跳出循环\n",
        "#输出双数\n",
        "i = 0\n",
        "while i < 10:\n",
        "    i=i+1\n",
        "    if i%2 >0:\n",
        "        continue\n",
        "    print(i)\n",
        "\n",
        "#break，跳出整个循环\n",
        "i=1\n",
        "while 1:\n",
        "    print(i)\n",
        "    i = i+1\n",
        "    if i >5:\n",
        "        break"
      ],
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "collapsed": true
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "### 2.2.4 try..except\n",
        "try:\n",
        "\n",
        "  代码1\n",
        "  \n",
        "except:\n",
        "\n",
        "  代码2\n",
        "  \n",
        "finally：\n",
        "\n",
        "  代码3\n",
        "\n",
        "代码1发生异常就执行代码2，无论正常与否都要执行代码3."
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#try和except\n",
        "#raise：主动触发异常\n",
        "try:\n",
        "    raise EOFError\n",
        "    print('EOFError 错误!')\n",
        "except EOFError:\n",
        "    print('EOFError异常。')\n",
        "\n",
        "#try和else\n",
        "list = [1, 2, 3, 4, 5, 6, 7, 8]\n",
        "try:\n",
        "    list.append(100)\n",
        "    print(list[8])\n",
        "except IndexError:\n",
        "    print('数组越界')\n",
        "else:\n",
        "    print(list)\n",
        "\n",
        "#try和finally\n",
        "list = [1, 2, 3, 4, 5, 6, 7, 8]\n",
        "try:\n",
        "    list.append(100)\n",
        "    print(list[10])\n",
        "except IndexError:\n",
        "    print('数组越界')\n",
        "finally:\n",
        "    print(list)\n",
        "\n",
        "#raise 抛出一个异常，一旦执行raise语句，后面的代码就不执行了,可以结合try 使用\n",
        "try:\n",
        "    raise EOFError\n",
        "    print('Hello World !')  #不执行\n",
        "except EOFError:\n",
        "    print('EOFError 错误')   #  打印 EOFError错误"
      ],
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "collapsed": true
      }
    },
    {
      "cell_type": "code",
      "source": [
        "try:\n",
        "    raise EOFError\n",
        "    print('EOFError 错误!')  #不执行\n",
        "except EOFError:\n",
        "    print('hello') "
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "hello\n"
          ]
        }
      ],
      "execution_count": 3,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "##with...as with语句时用于对try except finally 的简化\n",
        "f=open('file_name','r')\n",
        "try:\n",
        "    r=f.read()\n",
        "except:\n",
        "    pass\n",
        "finally:\n",
        "    f.close()\n",
        "    \n",
        "等价于\n",
        "\n",
        "with open('file_name','r') as f:\n",
        "    r=f.read()"
      ],
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "collapsed": true
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 2.3 常用关键字"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "help(\"keywords\")"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "Here is a list of the Python keywords.  Enter any keyword to get more help.\n",
            "\n",
            "False               def                 if                  raise\n",
            "None                del                 import              return\n",
            "True                elif                in                  try\n",
            "and                 else                is                  while\n",
            "as                  except              lambda              with\n",
            "assert              finally             nonlocal            yield\n",
            "break               for                 not                 \n",
            "class               from                or                  \n",
            "continue            global              pass                \n",
            "\n"
          ]
        }
      ],
      "execution_count": 4,
      "metadata": {}
    },
    {
      "cell_type": "markdown",
      "source": [
        "### 2.3.1内置常量False、None、True"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#False == 0 ,True == 1,type(False),type(None) "
      ],
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "collapsed": true
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "### 2.3.2 逻辑与 或 非 and or not¶\n",
        "优先级：not and or"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#  x and y     如果 x 为 False 、空、0，返 回 x，否则返回 y\n",
        "#  x or y      如果 x 为 False、 空、0，返回  y，否则返回x\n",
        "#  not  x     如果 x 为 False、 空、0，返回 True，否则返回False\n",
        "\n",
        "a = '1'\n",
        "b = 1\n",
        "a and b,a or y,not a"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 5,
          "data": {
            "text/plain": [
              "(1, '1', False)"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 5,
      "metadata": {}
    },
    {
      "cell_type": "markdown",
      "source": [
        "### 2.3.2 用来定义的关键字def、class、lambda\n",
        "* def : 定义一个函数或方法；\n",
        "* class: 定义一个类对象；\n",
        "* lambda：定义一个匿名函数；"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "class Student():\n",
        "    def __init__(self, name, age):\n",
        "        self.name = name\n",
        "        self.age = age\n",
        "\n",
        "    def info(self):\n",
        "        print('name:', self.name)\n",
        "        print('age:', self.age)\n",
        "\n",
        "stu = Student('didi', 20)\n",
        "stu.info()"
      ],
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "collapsed": true
      }
    },
    {
      "cell_type": "code",
      "source": [
        "def short_function(x):\n",
        "    return x * 2\n",
        "\n",
        "#等价于\n",
        "equiv_anon = lambda x: x * 2\n",
        "\n",
        "def apply_to_list(some_list, f):\n",
        "    return [f(x) for x in some_list]\n",
        "#虽然你可以直接编写[x *2for x in ints]，但是这里我们可以非常轻松地传入一个自定义运算给apply_to_list函数。\n",
        "ints = [4, 0, 1, 5, 6]\n",
        "apply_to_list(ints, lambda x: x * 2)"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 6,
          "data": {
            "text/plain": [
              "[8, 0, 2, 10, 12]"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 6,
      "metadata": {}
    },
    {
      "cell_type": "markdown",
      "source": [
        "### 2.3.3 控制流关键字（参考以上语句部分）\n",
        "if...elif...else...:条件判断；\n",
        "\n",
        "for...in...:对可迭代对象循环遍历\n",
        "\n",
        "for...in...else...:遍历正常完成则执行else后的代码；\n",
        "\n",
        "continue:终止本次循环，继续下一次循环；\n",
        "\n",
        "break：跳出循环；\n",
        "\n",
        "while：循环结构；\n",
        "\n",
        "return：函数返回值；"
      ],
      "metadata": {}
    },
    {
      "cell_type": "markdown",
      "source": [
        "### 2.3.4 变量命令空间关键字\n",
        "* global:将模块空间变量引入到局部空间修改；\n",
        "* nonlocal:将本局部空间的外层空间变量引入到本层局部空间修改，用来嵌套函数内；"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#定义全局变量：变量名全部大写\n",
        "NAME = 'didi'\n",
        "\n",
        "#得到NAME\n",
        "def get_NAME():\n",
        "    return NAME\n",
        "\n",
        "#重新设置NAME的值\n",
        "def set_NAME(name_value):\n",
        "    global NAME\n",
        "    NAME = name_value\n",
        "\n",
        "print(get_NAME())\n",
        "set_NAME('didididi')\n",
        "print(get_NAME())"
      ],
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "collapsed": true
      }
    },
    {
      "cell_type": "code",
      "source": [
        "#关键字nonlocal的作用与关键字global类似，使用nonlocal关键字可以在一个嵌套的函数中修改嵌套作用域中的变量\n",
        "def foo1():\n",
        "    num = 2\n",
        "    def foo2():\n",
        "        nonlocal num\n",
        "        num = 5\n",
        "    foo2()\n",
        "    print('num = ', num)\n",
        "\n",
        "foo1() # num = 5"
      ],
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "collapsed": true
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "### 2.3.5 del/yield"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "list = [1, 2, 3, 4, 5, 6, 7]\n",
        "del list[1]\n",
        "print(list)\n"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "[1, 3, 4, 5, 6, 7]\n"
          ]
        }
      ],
      "execution_count": 7,
      "metadata": {}
    },
    {
      "cell_type": "raw",
      "source": [
        "迭代器：所有你可以用在for...in...语句中的都是可迭代的:比如lists,strings,files...因为这些可迭代的对象你可以随意的读取所以非常方便易用,但是你必须把它们的值放到内存里,当它们有很多值时就会消耗太多的内存.\n",
        "生成器：生成器也是迭代器的一种,但是你只能迭代它们一次.原因很简单,因为它们不是全部存在内存里,它们只在要调用的时候在内存里生成。\n",
        "yield 是一个类似 return 的关键字，只是这个函数返回的是个生成器\n",
        "当你调用这个函数的时候，函数内部的代码并不立马执行 ，这个函数只是返回一个生成器对象\n",
        "当你使用for进行迭代的时候，函数中的代码才会执行"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "# #yield在函数中的功能类似于return，不同的是yield每次返回结果之后函数并没有退出，而是每次遇到yield关键字后返回相应结果，并保留函数当前的运行状态，等待下一次的调用。\n",
        "# 如果一个函数需要多次循环执行一个动作，并且每次执行的结果都是需要的，这种场景很适合使用yield实现。\n",
        "# 包含yield的函数成为一个生成器，生成器同时也是一个迭代器，支持通过next方法获取下一个值。\n",
        "\n",
        "def fun():\n",
        "    for i in range(20):\n",
        "        x=yield i\n",
        "        print('good',x)\n",
        "a=fun()\n",
        "a.__next__()\n",
        "x=a.send(5)\n",
        "#print(x)"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "good 5\n"
          ]
        }
      ],
      "execution_count": 9,
      "metadata": {}
    },
    {
      "cell_type": "markdown",
      "source": [
        "### 2.4 python输入及其格式化输出\n",
        "\n",
        "#### input输入\n",
        "\n",
        "在python2.7中式需要raw_input()"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#input可以接受一个参数，作为提示信息，当然参数可以是一个变量，方便输入更长的内容\n",
        "prompt = \"If you tell us who you are, we can personalize the messages you see.\"\n",
        "prompt += \"\\nWhat is your first name? \"\n",
        "name = input(prompt)\n",
        "print(\"\\nHello, \" + name + \"!\")"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "If you tell us who you are, we can personalize the messages you see.\n",
            "What is your first name? lyt\n",
            "\n",
            "Hello, lyt!\n"
          ]
        }
      ],
      "execution_count": 62,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#需要注意的是，接受的输入即使是数字也会被转化为字符串，所以要想获得数字输入，要加int()\n",
        "height = input(\"How tall are you, in inches? \")\n",
        "height = int(height)\n",
        "if height >= 36:\n",
        "    print(\"\\nYou're tall enough to ride!\")\n",
        "else:\n",
        "    print(\"\\nYou'll be able to ride when you're a little older.\")"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "How tall are you, in inches? 100\n",
            "\n",
            "You're tall enough to ride!\n"
          ]
        }
      ],
      "execution_count": 63,
      "metadata": {}
    },
    {
      "cell_type": "markdown",
      "source": [
        "#### 格式化输出"
      ],
      "metadata": {}
    },
    {
      "cell_type": "raw",
      "source": [
        "字符串格式化时百分号后面有不同的格式符号，代表要转换的不同类型，具体的表示符号如下面所示。 \n",
        "格式符号 表示类型\n",
        "  %s      字符串\n",
        "  %r    不管什么都打印出来(很多时候和%s类似，但是%r还会输出进一步的对象)\n",
        "  %d/%i   十进制整数\n",
        "  %u     十进制整数\n",
        "  %o     八进制整数\n",
        "  %x/%X   十六进制整数\n",
        "  %e/%E   科学计数\n",
        "  %f/%F   浮点数\n",
        "  %%      输出%"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "name = 'haobin'\n",
        "zone = 'com'\n",
        "print('www.%s.%s'%(name,zone))\n",
        "#小数\n",
        "mean = 0.17234\n",
        "print('%.2f%%' % (mean * 100))"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "www.haobin.com\n",
            "17.23%\n"
          ]
        }
      ],
      "execution_count": 13,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "##一样\n",
        "print(\"I am %s years old.\" % 22)\n",
        "print(\"I am %r years old.\" % 22)\n",
        "\n",
        "## 不一样,%r把单引号也输出了\n",
        "text = \"I am %d years old.\" % 22\n",
        "print(\"I said:%s.\" % text)\n",
        "print(\"I said:%r.\" % text)\n",
        "\n",
        "#不一样，%r把对象也输出了\n",
        "import datetime\n",
        "d =datetime.date.today()\n",
        "print(\"%s\" % d)\n",
        "print(\"%r\" % d)"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "I am 22 years old.\n",
            "I am 22 years old.\n",
            "I said:I am 22 years old..\n",
            "I said:'I am 22 years old.'.\n",
            "2019-09-02\n",
            "datetime.date(2019, 9, 2)\n"
          ]
        }
      ],
      "execution_count": 14,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#print的其他使用\n",
        "print('Hello')\n",
        "print('Hello',end=' ')#修改不用换行符结尾\n",
        "print('Cats','Dogs','mice')\n",
        "print('Cats','Dogs','mice',sep=',')"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Hello\n",
            "Hello Cats Dogs mice\n",
            "Cats,Dogs,mice\n"
          ]
        }
      ],
      "execution_count": 15,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#格式符号为数字时前面可以加为数和补缺位如：%[0][总位数][.][小数位数]来设定要转换的样式\n",
        "fValue = 8.123\n",
        "print('%06.2f'%fValue) # 保留宽度为6的2位小数浮点型"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "008.12\n"
          ]
        }
      ],
      "execution_count": 57,
      "metadata": {}
    },
    {
      "cell_type": "markdown",
      "source": [
        "#### format的使用\n",
        "位置匹配\n",
        "\n",
        "① 不带参数，即{}\n",
        "\n",
        "② 带数字参数，可调换顺序，即{1}、{2}\n",
        "\n",
        "③ 带关键字，即{a}、{to}"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "# 不带参数\n",
        "print('{} {}'.format('hello','world'))    # 结果：hello world\n",
        "# 带数字参数\n",
        "print('{0} {1}'.format('hello','world'))    # 结果：hello world\n",
        "# 参数顺序倒乱\n",
        "print('{0} {1} {0}'.format('hello','world'))    # 结果：hello world hello\n",
        "# 带关键字参数\n",
        "print('{a} {tom} {a}'.format(tom='hello',a='world'))    # 结果：world hello world"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "hello world\n",
            "hello world\n",
            "hello world hello\n",
            "world hello world\n"
          ]
        }
      ],
      "execution_count": 60,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "# 通过索引\n",
        "coord = (3, 5)\n",
        "print('X: {0[0]};  Y: {0[1]}'.format(coord))    # 结果：'X: 3;  Y: 5'\n",
        "# 通过key键参数\n",
        "a = {'a': 'test_a', 'b': 'test_b'}\n",
        "print('X: {0[a]};  Y: {0[b]}'.format(a))    # 结果：'X: test_a;  Y: test_b'"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "X: 3;  Y: 5\n",
            "X: test_a;  Y: test_b\n"
          ]
        }
      ],
      "execution_count": 61,
      "metadata": {}
    },
    {
      "cell_type": "raw",
      "source": [
        "我们还可以通过在格式化指示符后面添加一个冒号来进行精确格式化。"
      ],
      "metadata": {}
    },
    {
      "cell_type": "raw",
      "source": [
        "格式转换\n",
        "'b' - 二进制。将数字以2为基数进行输出。\n",
        "'c' - 字符。在打印之前将整数转换成对应的Unicode字符串。\n",
        "'d' - 十进制整数。将数字以10为基数进行输出。\n",
        "'o' - 八进制。将数字以8为基数进行输出。\n",
        "'x' - 十六进制。将数字以16为基数进行输出，9以上的位数用小写字母。\n",
        "'e' - 幂符号。用科学计数法打印数字。用'e'表示幂。\n",
        "'g' - 一般格式。将数值以fixed-point格式输出。当数值特别大的时候，用幂形式打印。\n",
        "'n' - 数字。当值为整数时和'd'相同，值为浮点数时和'g'相同。不同的是它会根据区域设置插入数字分隔符。\n",
        "'%' - 百分数。将数值乘以100然后以fixed-point('f')格式打印，值后面会有一个百分号。"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "print('{:b}'.format(3))\n",
        "print('{:c}'.format(20)) \n",
        "print('{:d}'.format(20)) \n",
        "print('{:o}'.format(20))\n",
        "print('{:x}'.format(20))  \n",
        "print('{:e}'.format(20))\n",
        "print('{:g}'.format(20.1))  \n",
        "print('{:f}'.format(20)) \n",
        "print('{:n}'.format(20))\n",
        "print('{:%}'.format(20))"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "11\n",
            "\u0014\n",
            "20\n",
            "24\n",
            "14\n",
            "2.000000e+01\n",
            "20.1\n",
            "20.000000\n",
            "20\n",
            "2000.000000%\n"
          ]
        }
      ],
      "execution_count": 59,
      "metadata": {}
    },
    {
      "cell_type": "markdown",
      "source": [
        "### 匿名（lambda）函数\n",
        "Python支持一种被称为匿名的、或lambda函数。它仅由单条语句组成，该语句的结果就是返回值。它是通过lambda关键字定义的，这个关键字没有别的含义，仅仅是说“我们正在声明的是一个匿名函数”。lambda函数之所以会被称为匿名函数，与def声明的函数不同，原因之一就是这种函数对象本身是没有提供名称name属性。"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "def short_function(x):\n",
        "    return x * 2\n",
        "\n",
        "#等价\n",
        "\n",
        "equiv_anon = lambda x: x * 2"
      ],
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "collapsed": true
      }
    },
    {
      "cell_type": "code",
      "source": [
        "def apply_to_list(some_list, f):\n",
        "    return [f(x) for x in some_list]\n",
        "#虽然你可以直接编写[x *2for x in ints]，但是这里我们可以非常轻松地传入一个自定义运算给apply_to_list函数。\n",
        "ints = [4, 0, 1, 5, 6]\n",
        "apply_to_list(ints, lambda x: x * 2)"
      ],
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "collapsed": true
      }
    },
    {
      "cell_type": "code",
      "source": [
        "def add_numbers(x, y):\n",
        "    return x + y\n",
        "add_five = lambda y: add_numbers(5, y)\n",
        "#add_numbers的第二个参数称为“柯里化的”（curried）。这里没什么特别花哨的东西，因为我们其实就只是定义了一个可以调用现有函数的新函数而已。"
      ],
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "collapsed": true
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "# 四、数据结构和序列"
      ],
      "metadata": {}
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 4.1 元组\n",
        "元组是一个固定长度，不可改变的Python序列对象。创建元组的最简单方式，是用逗号分隔一列值"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "tu=(1)\n",
        "tu2=(1,)\n",
        "tu3=(1,2,3,4)\n",
        "tu4=1,2,3,4\n",
        "type(tu4)"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 77,
          "data": {
            "text/plain": [
              "tuple"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 77,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#用tuple可以将任意序列或迭代器转换成元组\n",
        "tup = tuple('string')\n",
        "tup"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 78,
          "data": {
            "text/plain": [
              "('s', 't', 'r', 'i', 'n', 'g')"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 78,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#元组是不可变的对象，但如果元组中的某个对象是可变的，比如列表，可以进行修改\n",
        "tup = tuple(['foo', [1, 2], True])\n",
        "tup[1].append(3)\n",
        "tup"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 79,
          "data": {
            "text/plain": [
              "('foo', [1, 2, 3], True)"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 79,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#可以用加法和乘法串联\n",
        "tup1 = (4, None, 'foo') + (6, 0) + ('bar',)\n",
        "tup2 = ('foo', 'bar') * 5\n",
        "tup1,tup2"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 82,
          "data": {
            "text/plain": [
              "((4, None, 'foo', 6, 0, 'bar'),\n",
              " ('foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'bar'))"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 82,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#如果你想将元组赋值给类似元组的变量，Python会试图拆分等号右边的值\n",
        "tup = (4, 5, 6)\n",
        "a, b, c = tup\n",
        "a,b,c"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 85,
          "data": {
            "text/plain": [
              "(4, 5, 6)"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 85,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#简单的元组替换\n",
        "a , b = 1, 2\n",
        "b , a = a,b\n",
        "a,b"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 86,
          "data": {
            "text/plain": [
              "(2, 1)"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 86,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#Python最近新增了更多高级的元组拆分功能，允许从元组的开头“摘取”几个元素。\n",
        "#它使用了特殊的语法*rest，这也用在函数签名中以抓取任意长度列表的位置参数\n",
        "values = 1, 2, 3, 4, 5\n",
        "a,b,*rest = values\n",
        "a,b,rest\n",
        "#rest的部分是想要舍弃的部分，rest的名字不重要。作为惯用写法，许多Python程序员会将不需要的变量使用下划线，即*_"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 89,
          "data": {
            "text/plain": [
              "(1, 2, [3, 4, 5])"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 89,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#count（也适用于列表），它可以统计某个值得出现频率\n",
        "a = (1, 2, 2, 2, 3, 4, 2)\n",
        "a.count(2)"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 90,
          "data": {
            "text/plain": [
              "4"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 90,
      "metadata": {}
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 4.2 列表\n",
        "与元组对比，列表的长度可变、内容可以被修改。列表属于可变的数据类型，因此可以添执行加、删除，或者是搜索列表中的项目。列表可以嵌套"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "li = [1,2,3,4]\n",
        "li2 = ['a','b','c','d']\n",
        "li3 = [1,2,'a','b']\n",
        "li,li2,li3"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 108,
          "data": {
            "text/plain": [
              "([1, 2, 3, 4], ['a', 'b', 'c', 'd'], [1, 2, 'a', 'b'])"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 108,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "a_list = [2, 3, 7, None]\n",
        "a_list.append('dwarf')#append在列表末尾添加元素\n",
        "a_list.insert(1, 'red')#insert可以在特定的位置插入元素\n",
        "a_list"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 115,
          "data": {
            "text/plain": [
              "[2, 'red', 3, 7, None, 'dwarf']"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 115,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "a_list.pop(2)#pop移除并返回指定位置的元素"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 111,
          "data": {
            "text/plain": [
              "3"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 111,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "a_list.append('red')#再末尾加上'red'。这样就有两个'red'值\n",
        "a_list.remove('red')#remove会先寻找第一个值并除去\n",
        "a_list"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 118,
          "data": {
            "text/plain": [
              "[2, 3, 7, None, 'dwarf', 'red']"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 118,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#extend方法可以追加多个元素\n",
        "x = [4, None, 'foo']\n",
        "x.extend([7, 8, (2, 3)])\n",
        "x"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 119,
          "data": {
            "text/plain": [
              "[4, None, 'foo', 7, 8, (2, 3)]"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 119,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#切片可以选取大多数序列类型的一部分，切片的基本形式是在方括号中使用。\n",
        "#切片的起始元素是包括的，不包含结束元素。\n",
        "seq = [7, 2, 3, 7, 5, 6, 0, 1]\n",
        "seq[1:5],seq[:5]#start或stop都可以被省略，省略之后，分别默认序列的开头和结尾"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 121,
          "data": {
            "text/plain": [
              "([2, 3, 7, 5], [7, 2, 3, 7, 5])"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 121,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#遍历\n",
        "lists = [\"m1\", 1900, \"m2\", 2000]\n",
        "#1.使用iter()\n",
        "for val in iter(lists):\n",
        "    print(val)\n",
        "#2.enumerate遍历方法\n",
        "for i, val in enumerate(lists):\n",
        "    print(i, val)\n",
        "#3.索引遍历\n",
        "for index in range(len(lists)):\n",
        "    print(lists[index])"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "m1\n",
            "1900\n",
            "m2\n",
            "2000\n",
            "0 m1\n",
            "1 1900\n",
            "2 m2\n",
            "3 2000\n"
          ]
        }
      ],
      "execution_count": 77,
      "metadata": {}
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 4.3 字典\n",
        "字典可能是Python最为重要的数据结构。它更为常见的名字是哈希映射或关联数组。它是键值对的大小可变集合，键和值都是Python对象。字典使用花括号{}包括，键和值之间用冒号：分割，每对键-值”用逗号，分割 键必须唯一，即一个键不能对应多个值，不过多个键可以指向一个值。"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#创建字典的方法之一是使用尖括号，用冒号分隔键和值：\n",
        "empty_dict = {}\n",
        "d1 = {'a' : 'some value', 'b' : [1, 2, 3, 4]}\n",
        "d1"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 5,
          "data": {
            "text/plain": [
              "{'a': 'some value', 'b': [1, 2, 3, 4]}"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 5,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "d1[7] = 'an integer'#插入字典中的元素，7为key，'an integer'为value\n",
        "d1"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 6,
          "data": {
            "text/plain": [
              "{7: 'an integer', 'a': 'some value', 'b': [1, 2, 3, 4]}"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 6,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#del关键字或pop方法（返回值的同时删除键）删除值\n",
        "d1[5] = 'some value'\n",
        "print(d1)\n",
        "d1['dummy'] = 'another value'\n",
        "print(d1)\n",
        "del d1[5]\n",
        "print(d1)"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "{'a': 'some value', 'b': [1, 2, 3, 4], 7: 'an integer', 5: 'some value'}\n",
            "{'a': 'some value', 'b': [1, 2, 3, 4], 7: 'an integer', 5: 'some value', 'dummy': 'another value'}\n",
            "{'a': 'some value', 'b': [1, 2, 3, 4], 7: 'an integer', 'dummy': 'another value'}\n"
          ]
        }
      ],
      "execution_count": 7,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "ret = d1.pop('dummy')\n",
        "ret,d1"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 8,
          "data": {
            "text/plain": [
              "('another value', {7: 'an integer', 'a': 'some value', 'b': [1, 2, 3, 4]})"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 8,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#keys和values是字典的键和值的迭代器方法。虽然键值对没有顺序，这两个方法可以用相同的顺序输出键和值\n",
        "list(d1.keys()),list(d1.values())"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 9,
          "data": {
            "text/plain": [
              "(['a', 'b', 7], ['some value', [1, 2, 3, 4], 'an integer'])"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 9,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#keys()返回键,values()返回值和items()方法返回键值对\n",
        "#返回结果并不是真正的列表，因此不能被append和修改，但可以使用for循环或者强制转换\n",
        "#字典转为列表\n",
        "spam =  {'color':'red','age':42}\n",
        "spam.values()\n",
        "for i in spam.items():\n",
        "    print(i)\n",
        "#把返回结果换为列表\n",
        "list(spam.keys())"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "('color', 'red')\n",
            "('age', 42)\n"
          ]
        },
        {
          "output_type": "execute_result",
          "execution_count": 12,
          "data": {
            "text/plain": [
              "['color', 'age']"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 12,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#字典的遍历\n",
        "#1.遍历key值 在使用上，for key in a和 for key in a.keys():完全等价。\n",
        "a={'a': '1', 'b': '2', 'c': '3'}\n",
        "print(\"遍历key值:\")\n",
        "for key in a:\n",
        "    print(key+':'+a[key])\n",
        "#2.遍历value值\n",
        "print(\"遍历value值:\")\n",
        "for value in a.values():\n",
        "    print(value)\n",
        "#3.遍历字典项\n",
        "print(\"遍历字典项:\")\n",
        "for kv in a.items():\n",
        "    print(kv)\n",
        "#4.遍历字典健值\n",
        "print(\"遍历字典健值:\")\n",
        "for key,value in a.items():\n",
        "    print(key+':'+value)"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "遍历key值:\n",
            "a:1\n",
            "b:2\n",
            "c:3\n",
            "遍历value值:\n",
            "1\n",
            "2\n",
            "3\n",
            "遍历字典项:\n",
            "('a', '1')\n",
            "('b', '2')\n",
            "('c', '3')\n",
            "遍历字典健值:\n",
            "a:1\n",
            "b:2\n",
            "c:3\n"
          ]
        }
      ],
      "execution_count": 76,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#update方法可以将一个字典与另一个融合\n",
        "d1.update({'b' : 'foo', 'c' : 12})\n",
        "d1"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 10,
          "data": {
            "text/plain": [
              "{7: 'an integer', 'a': 'some value', 'b': 'foo', 'c': 12}"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 10,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#字典总是明确地记录键和值之间的关联关系，但获取字典的元素时，获取顺序是不可预测的。\n",
        "#要以特定的顺序返回元素，一种办法是在for 循环中对返回的键进行排序。\n",
        "favorite_languages = {\n",
        "    'jen': 'python',\n",
        "    'sarah': 'c',\n",
        "    'edward': 'ruby',\n",
        "    'phil': 'python',\n",
        "}\n",
        "for name in sorted(favorite_languages.keys()):\n",
        "    print(name.title() + \", thank you for taking the poll.\")"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Edward, thank you for taking the poll.\n",
            "Jen, thank you for taking the poll.\n",
            "Phil, thank you for taking the poll.\n",
            "Sarah, thank you for taking the poll.\n"
          ]
        }
      ],
      "execution_count": 13,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#setdefault方法,比defaultdict方便,为字典中某个键设置一个默认值，当该键没有任何值时使用它。\n",
        "#空字典可以直接增加变量，但是如果在Python中如果访问字典中不存在的键，会引发KeyError异常。\n",
        "#由于键值是空的，所以不能直接访问\n",
        "words = ['apple', 'bat', 'bar', 'atom', 'book']\n",
        "by_letter = {}\n",
        "for word in words:\n",
        "    letter = word[0]\n",
        "    by_letter.setdefault(letter, []).append(word)\n",
        "by_letter"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 15,
          "data": {
            "text/plain": [
              "{'a': ['apple', 'atom'], 'b': ['bat', 'bar', 'book']}"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 15,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#collections模块有一个很有用的类，defaultdict，它可以进一步简化上面。传递类型或函数以生成每个位置的默认值\n",
        "##defaultdict就是一个本身带有默认值的dict\n",
        "#defaultdict类的初始化函数受一个类型作为参数，当接所访问的键不存在的时候，可以实例化一个值作为默认值\n",
        "from collections import defaultdict\n",
        "by_letter = defaultdict(list)\n",
        "for word in words:\n",
        "    by_letter[word[0]].append(word)"
      ],
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "collapsed": true
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# 字典转成dataframe\n",
        "#1.直接使用pd.DataFrame()。\n",
        "dict = {'a':'apple','b':'banana'}\n",
        "import pandas as pd\n",
        "df = pd.DataFrame([dict])\n",
        "df"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 66,
          "data": {
            "text/html": [
              "<div>\n",
              "<style scoped>\n",
              "    .dataframe tbody tr th:only-of-type {\n",
              "        vertical-align: middle;\n",
              "    }\n",
              "\n",
              "    .dataframe tbody tr th {\n",
              "        vertical-align: top;\n",
              "    }\n",
              "\n",
              "    .dataframe thead th {\n",
              "        text-align: right;\n",
              "    }\n",
              "</style>\n",
              "<table border=\"1\" class=\"dataframe\">\n",
              "  <thead>\n",
              "    <tr style=\"text-align: right;\">\n",
              "      <th></th>\n",
              "      <th>a</th>\n",
              "      <th>b</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "      <th>0</th>\n",
              "      <td>apple</td>\n",
              "      <td>banana</td>\n",
              "    </tr>\n",
              "  </tbody>\n",
              "</table>\n",
              "</div>"
            ],
            "text/plain": [
              "       a       b\n",
              "0  apple  banana"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 66,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#2.使用DataFrame的from_dict()方法。\n",
        "df = pd.DataFrame.from_dict(dict,orient='index')\n",
        "df = df.reset_index().rename(columns = {'index':'id'})\n",
        "df"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 48,
          "data": {
            "text/html": [
              "<div>\n",
              "<style scoped>\n",
              "    .dataframe tbody tr th:only-of-type {\n",
              "        vertical-align: middle;\n",
              "    }\n",
              "\n",
              "    .dataframe tbody tr th {\n",
              "        vertical-align: top;\n",
              "    }\n",
              "\n",
              "    .dataframe thead th {\n",
              "        text-align: right;\n",
              "    }\n",
              "</style>\n",
              "<table border=\"1\" class=\"dataframe\">\n",
              "  <thead>\n",
              "    <tr style=\"text-align: right;\">\n",
              "      <th></th>\n",
              "      <th>id</th>\n",
              "      <th>0</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "      <th>0</th>\n",
              "      <td>a</td>\n",
              "      <td>apple</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>1</th>\n",
              "      <td>b</td>\n",
              "      <td>banana</td>\n",
              "    </tr>\n",
              "  </tbody>\n",
              "</table>\n",
              "</div>"
            ],
            "text/plain": [
              "  id       0\n",
              "0  a   apple\n",
              "1  b  banana"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 48,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#3.将字典转变为Series，再转为DataFrame。\n",
        "df = pd.DataFrame(pd.Series(dict), columns=['fruits'])\n",
        "df = df.reset_index().rename(columns={'index':'id'})\n",
        "df"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 41,
          "data": {
            "text/html": [
              "<div>\n",
              "<style scoped>\n",
              "    .dataframe tbody tr th:only-of-type {\n",
              "        vertical-align: middle;\n",
              "    }\n",
              "\n",
              "    .dataframe tbody tr th {\n",
              "        vertical-align: top;\n",
              "    }\n",
              "\n",
              "    .dataframe thead th {\n",
              "        text-align: right;\n",
              "    }\n",
              "</style>\n",
              "<table border=\"1\" class=\"dataframe\">\n",
              "  <thead>\n",
              "    <tr style=\"text-align: right;\">\n",
              "      <th></th>\n",
              "      <th>id</th>\n",
              "      <th>fruits</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "      <th>0</th>\n",
              "      <td>a</td>\n",
              "      <td>apple</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>1</th>\n",
              "      <td>b</td>\n",
              "      <td>banana</td>\n",
              "    </tr>\n",
              "  </tbody>\n",
              "</table>\n",
              "</div>"
            ],
            "text/plain": [
              "  id  fruits\n",
              "0  a   apple\n",
              "1  b  banana"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 41,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#4.reset_index().rename()方法，将作为index的keys变为DataFrame中的一列\n",
        "df = pd.DataFrame([dict]).T\n",
        "df = df.reset_index().rename(columns={'index':'id'})\n",
        "df"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 42,
          "data": {
            "text/html": [
              "<div>\n",
              "<style scoped>\n",
              "    .dataframe tbody tr th:only-of-type {\n",
              "        vertical-align: middle;\n",
              "    }\n",
              "\n",
              "    .dataframe tbody tr th {\n",
              "        vertical-align: top;\n",
              "    }\n",
              "\n",
              "    .dataframe thead th {\n",
              "        text-align: right;\n",
              "    }\n",
              "</style>\n",
              "<table border=\"1\" class=\"dataframe\">\n",
              "  <thead>\n",
              "    <tr style=\"text-align: right;\">\n",
              "      <th></th>\n",
              "      <th>id</th>\n",
              "      <th>0</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "      <th>0</th>\n",
              "      <td>a</td>\n",
              "      <td>apple</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>1</th>\n",
              "      <td>b</td>\n",
              "      <td>banana</td>\n",
              "    </tr>\n",
              "  </tbody>\n",
              "</table>\n",
              "</div>"
            ],
            "text/plain": [
              "  id       0\n",
              "0  a   apple\n",
              "1  b  banana"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 42,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#5.多个值，通过创建子字典\n",
        "test_0 = {\"id\":[1,1,2,3,3,4,5,5],\"price\":[5,6,8,3,4,6,9,5],\"amount\":[1,1,2,1,1,1,2,1],\"status\":['sale','sale','no','no','sale','no','sale','no']} \n",
        "index = {'id','price','amount'}   #创建存储想要的key的集合\n",
        "test_1 = {key:value for key,value in test_0.items()if key in index}   #建立子字典\n",
        "pd.DataFrame(test_1)"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 73,
          "data": {
            "text/html": [
              "<div>\n",
              "<style scoped>\n",
              "    .dataframe tbody tr th:only-of-type {\n",
              "        vertical-align: middle;\n",
              "    }\n",
              "\n",
              "    .dataframe tbody tr th {\n",
              "        vertical-align: top;\n",
              "    }\n",
              "\n",
              "    .dataframe thead th {\n",
              "        text-align: right;\n",
              "    }\n",
              "</style>\n",
              "<table border=\"1\" class=\"dataframe\">\n",
              "  <thead>\n",
              "    <tr style=\"text-align: right;\">\n",
              "      <th></th>\n",
              "      <th>amount</th>\n",
              "      <th>id</th>\n",
              "      <th>price</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "      <th>0</th>\n",
              "      <td>1</td>\n",
              "      <td>1</td>\n",
              "      <td>5</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>1</th>\n",
              "      <td>1</td>\n",
              "      <td>1</td>\n",
              "      <td>6</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>2</th>\n",
              "      <td>2</td>\n",
              "      <td>2</td>\n",
              "      <td>8</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>3</th>\n",
              "      <td>1</td>\n",
              "      <td>3</td>\n",
              "      <td>3</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>4</th>\n",
              "      <td>1</td>\n",
              "      <td>3</td>\n",
              "      <td>4</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>5</th>\n",
              "      <td>1</td>\n",
              "      <td>4</td>\n",
              "      <td>6</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>6</th>\n",
              "      <td>2</td>\n",
              "      <td>5</td>\n",
              "      <td>9</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>7</th>\n",
              "      <td>1</td>\n",
              "      <td>5</td>\n",
              "      <td>5</td>\n",
              "    </tr>\n",
              "  </tbody>\n",
              "</table>\n",
              "</div>"
            ],
            "text/plain": [
              "   amount  id  price\n",
              "0       1   1      5\n",
              "1       1   1      6\n",
              "2       2   2      8\n",
              "3       1   3      3\n",
              "4       1   3      4\n",
              "5       1   4      6\n",
              "6       2   5      9\n",
              "7       1   5      5"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 73,
      "metadata": {
        "scrolled": true
      }
    },
    {
      "cell_type": "code",
      "source": [
        "#根据key 找value  \n",
        "d = {'a' : [1, 2, 3], 'b' : [4, 5],'c':[1,2,3,4] }\n",
        "key = ['a','c']\n",
        "value=[]\n",
        "for k in key:\n",
        "    value.append(d[k])\n",
        "value"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 64,
          "data": {
            "text/plain": [
              "[[1, 2, 3], [1, 2, 3, 4]]"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 64,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#根据value找key\n",
        "d = { 'a' : [1, 2, 3], 'b' : [4, 5],'c':[1,2,3] }\n",
        "value = [1,3]\n",
        "t=[k for k,v in d.items() if v == [1,2,3]]\n",
        "print(t)"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "['a', 'c']\n"
          ]
        }
      ],
      "execution_count": 54,
      "metadata": {}
    },
    {
      "cell_type": "markdown",
      "source": [
        "##  4.4 集合\n",
        "集合是无序的不可重复的元素的集合。你可以把它当做字典，但是只有键没有值。"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#两种方式创建集合：通过set函数或使用尖括号set语句\n",
        "set([2, 2, 2, 1, 3, 3]),{2, 2, 2, 1, 3, 3}"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 16,
          "data": {
            "text/plain": [
              "({1, 2, 3}, {1, 2, 3})"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 16,
      "metadata": {}
    },
    {
      "cell_type": "raw",
      "source": [
        "集合支持合并、交集、差分和对称差等数学集合运算\n",
        "函数                     替代语法              说明\n",
        "a.union(b)                  a|b          集合a和b中的所有不重复元素\n",
        "a.update(b)                 al=b          设定集合a中的元素为a与b的合并\n",
        "a.intersection(b)             a&b          a和b中交叉的元素\n",
        "a.intersection_update(b)        a&=b          设定集合a中的元素为a与b的交叉\n",
        "a.difference(b)              a-b          存在于a但不存在于b的元素\n",
        "a.difference_update(b)          a-=b         设定集合a中的元素为a与b的差\n",
        "a.symmetric_difference(b)        a^b          只在a或只在b的元素\n",
        "a.symmetric_difference_update(b)   a^=b         集合a中的元素为只在a或只在b的元素"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "a = {1, 2, 3, 4, 5}\n",
        "b = {3, 4, 5, 6, 7, 8}\n",
        "a.union(b),a.intersection(b)"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 18,
          "data": {
            "text/plain": [
              "({1, 2, 3, 4, 5, 6, 7, 8}, {3, 4, 5})"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 18,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "c = a.copy()\n",
        "c |= b\n",
        "c"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 19,
          "data": {
            "text/plain": [
              "{1, 2, 3, 4, 5, 6, 7, 8}"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 19,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "d = a.copy()\n",
        "d &= b\n",
        "d"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 20,
          "data": {
            "text/plain": [
              "{3, 4, 5}"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 20,
      "metadata": {}
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 4.5常用序列函数"
      ],
      "metadata": {}
    },
    {
      "cell_type": "markdown",
      "source": [
        "### enumerate函数"
      ],
      "metadata": {}
    },
    {
      "cell_type": "raw",
      "source": [
        "enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列，同时列出数据和数据下标，一般用在 for 循环当中。 enumerate(sequence, [start=0])\n",
        "sequence  一个序列、迭代器或其他支持迭代对象。\n",
        "start  下标起始位置。"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "seasons = ['Spring','Summer','Fall','Winter']\n",
        "for i,ele in enumerate(seasons):\n",
        "    print(i,ele)"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "0 Spring\n",
            "1 Summer\n",
            "2 Fall\n",
            "3 Winter\n"
          ]
        }
      ],
      "execution_count": 124,
      "metadata": {}
    },
    {
      "cell_type": "markdown",
      "source": [
        "### sorted函数\n",
        "sorted函数可以从任意序列的元素返回一个新的排好序的列表"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "sorted([7, 1, 2, 6, 0, 3, 2]),sorted('horse race')"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 126,
          "data": {
            "text/plain": [
              "([0, 1, 2, 2, 3, 6, 7], [' ', 'a', 'c', 'e', 'e', 'h', 'o', 'r', 'r', 's'])"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 126,
      "metadata": {}
    },
    {
      "cell_type": "markdown",
      "source": [
        "### zip函数\n",
        "zip可以将多个列表、元组或其它序列成对组合成一个元组列表.zip可以处理任意多的序列，元素的个数取决于最短的序列"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "seq1 = ['foo', 'bar', 'baz']\n",
        "\n",
        "seq2 = ['one', 'two', 'three']\n",
        "\n",
        "zipped = zip(seq1, seq2)\n",
        "\n",
        "list(zipped)"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 1,
          "data": {
            "text/plain": [
              "[('foo', 'one'), ('bar', 'two'), ('baz', 'three')]"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 1,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "seq3 = [False, True]\n",
        "list(zip(seq1, seq2, seq3))"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 2,
          "data": {
            "text/plain": [
              "[('foo', 'one', False), ('bar', 'two', True)]"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 2,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "#zip的常见用法之一是同时迭代多个序列，可能结合enumerate使用\n",
        "for i, (a, b) in enumerate(zip(seq1, seq2)):\n",
        "    print('{0}: {1}, {2}'.format(i, a, b))"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "0: foo, one\n",
            "1: bar, two\n",
            "2: baz, three\n"
          ]
        }
      ],
      "execution_count": 3,
      "metadata": {}
    },
    {
      "cell_type": "markdown",
      "source": [
        "### reversed函数"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "list(reversed(range(10)))#reversed可以从后向前迭代一个序列"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 4,
          "data": {
            "text/plain": [
              "[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 4,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "help(\"keywords\")"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "Here is a list of the Python keywords.  Enter any keyword to get more help.\n",
            "\n",
            "False               def                 if                  raise\n",
            "None                del                 import              return\n",
            "True                elif                in                  try\n",
            "and                 else                is                  while\n",
            "as                  except              lambda              with\n",
            "assert              finally             nonlocal            yield\n",
            "break               for                 not                 \n",
            "class               from                or                  \n",
            "continue            global              pass                \n",
            "\n"
          ]
        }
      ],
      "execution_count": 23,
      "metadata": {}
    },
    {
      "cell_type": "raw",
      "source": [
        " x and y     如果 x 为 False 、空、0，返 回 x，否则返回 y\n",
        " x or y      如果 x 为 False、 空、0，返回  y，否则返回x\n",
        " not  x     如果 x 为 False、 空、0，返回 True，否则返回False"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "a = '1'\n",
        "b = 1\n",
        "a and b,a or y,not a"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "execution_count": 28,
          "data": {
            "text/plain": [
              "(1, '1', False)"
            ]
          },
          "metadata": {}
        }
      ],
      "execution_count": 28,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [],
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "collapsed": true
      }
    }
  ],
  "metadata": {
    "kernelspec": {
      "name": "python3",
      "language": "python",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python",
      "version": "3.6.1",
      "mimetype": "text/x-python",
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "pygments_lexer": "ipython3",
      "nbconvert_exporter": "python",
      "file_extension": ".py"
    },
    "varInspector": {
      "cols": {
        "lenName": 16,
        "lenType": 16,
        "lenVar": 40
      },
      "kernels_config": {
        "python": {
          "delete_cmd_postfix": "",
          "delete_cmd_prefix": "del ",
          "library": "var_list.py",
          "varRefreshCmd": "print(var_dic_list())"
        },
        "r": {
          "delete_cmd_postfix": ") ",
          "delete_cmd_prefix": "rm(",
          "library": "var_list.r",
          "varRefreshCmd": "cat(var_dic_list()) "
        }
      },
      "types_to_exclude": [
        "module",
        "function",
        "builtin_function_or_method",
        "instance",
        "_Feature"
      ],
      "window_display": false
    },
    "kernel_info": {
      "name": "python3"
    },
    "nteract": {
      "version": "0.14.5"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 2
}